import { DataSource, dataSourceGetMappingSQL } from './data-source';
import { ConnectorDataSource, queryForMap, query, queryOne, execute } from '../connector';
import { metaDataGetMetaDataObjectByIdentifier, metaDataGetObjectProperties } from '../meta-data';
import { MetaDataObjectProperty, DataSourceDomainMappingType } from '../types';
import { dataSourceDomainGetMappingObjectByObjIdentifier, dataSourceDomainGetMappingPropertyByObjIdentifier } from './domain-mapping';

export class DataSourceDomainConnector {

    dataSource: DataSource;

    connectorDataSource: ConnectorDataSource;

    constructor(ds: DataSource) {
        this.dataSource = ds;
        let options: any = JSON.parse(ds.storage_options);

        this.connectorDataSource = {
            protocol: 'mysql',
            url: options.url,
            database_type: 'mysql',
            options: options,
        };
    }

    // 查询对象下所有的属性，绘制表头
    public async queryHeaders(objectIdentifier: string): Promise<Array<MetaDataObjectProperty>> {
        //查询所有的属性
        let properties = await metaDataGetObjectProperties(objectIdentifier, 1, 1000);
        //
        return properties.data;
    }

    // 查询对象下所有的数据
    public async queryValues(objectIdentifier: string): Promise<Array<Array<any>>> {
        //查询所有的属性
        let { data: properties } = await metaDataGetObjectProperties(objectIdentifier, 1, 1000);

        let metaObject = await metaDataGetMetaDataObjectByIdentifier(objectIdentifier);

        //查询映射关系
        let mappingObj = await dataSourceDomainGetMappingObjectByObjIdentifier(this.dataSource.id, objectIdentifier);

        let sql: string | null = null;

        if (mappingObj && mappingObj.mappingType === 'SQL' && mappingObj.objectSQL.length > 0) {
            //sql
            sql = mappingObj.objectSQL;
        } else if (mappingObj && mappingObj.mappingType === 'TABLE') {
            //table
            sql = `select * from ${mappingObj.tableIdentifier}`
        } else {
            //table
            sql = `select * from ${metaObject.name}`
        }
        console.log('执行sql', properties, sql, this.connectorDataSource);
        //执行SQL
        let data: Array<any> = await queryForMap(this.connectorDataSource, sql, [], {});

        if (!data || data.length <= 0) {
            return [];
        }

        let keys: string[] = [];

        if (mappingObj && mappingObj.mappingType === 'SQL' && mappingObj.objectSQL.length > 0) {
            //sql, 
            keys = properties.map((p, index) => {
                return getKeyFromPropertyIdentifier(p.identifier);
            });
        } else if (mappingObj && mappingObj.mappingType === 'TABLE') {
            //table
            //获取到属性的映射
            let propsMapping = await dataSourceDomainGetMappingPropertyByObjIdentifier(this.dataSource.id, objectIdentifier);
            console.log('propsMapping', propsMapping);
            keys = properties.map((p, index) => {
                if (propsMapping) {
                    for (let i = 0; i < propsMapping.length; i++) {
                        if (propsMapping[i].propertyIdentifier === p.identifier) {
                            return propsMapping[i].columnIdentifier;
                        }
                    }
                }
                return getKeyFromPropertyIdentifier(p.name);
            });
        } else {
            keys = properties.map((p, index) => {
                return getKeyFromPropertyIdentifier(p.name);
            });
        }
        console.log(keys, data);
        return data.map((item, index) => {
            return keys.map((key, pindex) => {
                return item[key];
            });
        });
    }
}

const getKeyFromPropertyIdentifier = (propertyIdentifier: string): string => {
    let arr = propertyIdentifier.split('.');
    if (arr && arr.length > 0) {
        return arr[arr.length - 1];
    }
    return propertyIdentifier;
}

export default {};